
/*
 * ----------------------
 * Includes
 * ----------------------
 */

 // Standard
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

// SDL
#include <SDL.h>
#include <SDL/SDL_ttf.h>

// GUI
#include "elder_gui.h"

// Context
#include "context.h"

/*
 * ----------------------
 * Defines
 * ----------------------
 */

// Batt Gauge position
#define BATT_GAUGE_X 3
#define BATT_GAUGE_Y 226
#define BATT_GAUGE_H 30
#define BATT_GAUGE_W 5

// Batt Gauge values in mV
#define BATT_GAUGE_MAX 1400
#define BATT_GAUGE_MIN 1000

/*
 * ----------------------
 * Global variables
 * ----------------------
 */

 extern SDL_Surface* screen;
 extern context currentContext;



/*
* --------------------
* Progress bars update functions
* --------------------
*/

SDL_Color getBattColor(int battValue)
{
	SDL_Color color = COLOR_BLACK;
		
    // Color depends on the batteries level
    if ( battValue < BATT_GAUGE_MIN + (BATT_GAUGE_MAX - BATT_GAUGE_MIN)/3 )
    {
    	
        color.r = 0xFF; // Red
        // Display alert
    }
    else if( battValue < BATT_GAUGE_MIN +  2*( BATT_GAUGE_MAX - BATT_GAUGE_MIN )/3 )
    {
        color.r = 0xFF; // Yellow
        color.g = 0xFF;
    }
    else
    {
    	color.g = 0xFF; // Green
        
    }
    
    return color;


}

	

void updateBatteries(void)
{

    SDL_Rect battGauge;

	SDL_Color color;
	
    int lowestElValue;
    // Test witch batterie element is the lowest
    if ( currentContext.batteries.el1Voltage < currentContext.batteries.el2Voltage )
    {
        lowestElValue=currentContext.batteries.el1Voltage;
    }else
    {
        lowestElValue=currentContext.batteries.el2Voltage;
    }

    // Size of the Gauge depends on the batt level
    battGauge.x=BATT_GAUGE_X;
    battGauge.y=BATT_GAUGE_Y - 30 * (lowestElValue - BATT_GAUGE_MIN)/(BATT_GAUGE_MAX - BATT_GAUGE_MIN) + 30;
    battGauge.w=BATT_GAUGE_W;
    battGauge.h=BATT_GAUGE_H + 30 * (lowestElValue - BATT_GAUGE_MIN)/(BATT_GAUGE_MAX - BATT_GAUGE_MIN) - 30;

    // Erase last gauge
    SDL_FillRect(screen, &battGauge,0);
	
	color = getBattColor(lowestElValue);
	
    SDL_FillRect(screen, &battGauge,SDL_MapRGB(screen->format, color.r, color.g, color.b));
    
    SDL_UpdateRect(screen, BATT_GAUGE_X, BATT_GAUGE_Y, BATT_GAUGE_W, BATT_GAUGE_H);
	
}

